package com.ygq;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ExcelWriteTest
 *
 * @author Yin Guiqing
 */
public class ExcelWriteTest {
    static final String PATH = "src\\";

    /**
     * xls 文件的写测试
     */
    @Test
    public void testWrite2003() throws IOException {
        // 1. 创建工作簿
        Workbook workbook = new HSSFWorkbook();
        // 2. 创建工作表
        Sheet sheet = workbook.createSheet("英雄表");
        // 3. 创建行
        Row row1 = sheet.createRow(0);
        // 4. 创建单元格并设置值
        Cell cell1A = row1.createCell(0);
        cell1A.setCellValue("编号");
        Cell cell1B = row1.createCell(1);
        cell1B.setCellValue("名称");
        Cell cell1C = row1.createCell(2);
        cell1C.setCellValue("阵营");

        Row row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("#001");
        row2.createCell(1).setCellValue("德玛西亚之力-盖伦");
        row2.createCell(2).setCellValue("德玛西亚");
        Row row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("#002");
        row3.createCell(1).setCellValue("无双剑姬-菲奥娜");
        row3.createCell(2).setCellValue("德玛西亚");

        // 5. 将文件写出
        FileOutputStream outputStream = new FileOutputStream(PATH + "英雄表2003.xls");
        workbook.write(outputStream);
        // 6. 关闭流
        workbook.close();
        outputStream.close();
        System.out.println("【英雄表2003.xls】生成完毕！");
    }

    /**
     * xlsx 文件的写测试
     * <p>
     * 因为是面向接口编程，所以除了 Workbook 的实现对象和文件后缀名，其他代码不用改动
     */
    @Test
    public void testWrite2007() throws IOException {
        // 1. 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 2. 创建工作表
        Sheet sheet = workbook.createSheet("英雄表");
        // 3. 创建行
        Row row1 = sheet.createRow(0);
        // 4. 创建单元格并设置值
        Cell cell1A = row1.createCell(0);
        cell1A.setCellValue("编号");
        Cell cell1B = row1.createCell(1);
        cell1B.setCellValue("名称");
        Cell cell1C = row1.createCell(2);
        cell1C.setCellValue("阵营");

        Row row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("#001");
        row2.createCell(1).setCellValue("德玛西亚之力-盖伦");
        row2.createCell(2).setCellValue("德玛西亚");
        Row row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("#002");
        row3.createCell(1).setCellValue("无双剑姬-菲奥娜");
        row3.createCell(2).setCellValue("德玛西亚");

        // 5. 将文件写出
        FileOutputStream outputStream = new FileOutputStream(PATH + "英雄表2007.xlsx");
        workbook.write(outputStream);
        // 6. 关闭流
        workbook.close();
        outputStream.close();
        System.out.println("【英雄表2007.xlsx】生成完毕！");
    }
}
